package com.suneast.suneaststore.modules.personal.address;

import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.suneast.suneaststore.R;
import com.suneast.suneaststore.modules.personal.address.adapter.AddressListAdapter;
import com.suneast.suneaststore.bean.personal.address.AddressBean;
import com.suneast.suneaststore.modules.personal.address.event.DeletedAddress;
import com.suneast.suneaststore.modules.personal.address.event.GotAddressList;
import com.suneast.suneaststore.modules.personal.address.event.SetDefaultAddressResult;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.ui.dialog.CancelConfirmDialog;
import com.suneast.suneaststore.ui.fragments.BaseFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

public class AddressListFragment extends BaseFragment implements CancelConfirmDialog.ConfirmBtnClickListener {
    private static final int ADD_ADDRESS_REQUEST_CODE = 0;
    private static final int MODIFY_ADDRESS_REQUEST_CODE = 1;
    public static final int ADD_ADDRESS_RESULT = 1;
    public static final int MODIFY_ADDRESS_RESULT = 2;

    public final static String KEY_TYPE = "key_type";

    @Override
    public @LayoutRes
    int setLayout() {
        return R.layout.fragment_address_list;
    }

    private int startType = 0; // 启动该界面的目的 0:编辑收货地址列表  1: 切换收货地址

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        EventBus.getDefault().register(this);
        Bundle bundle = getArguments();
        if (bundle != null) {
            startType = bundle.getInt(KEY_TYPE, 0);
        }
        initView();
        AddressHandler.requestAddressList();
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (requestCode == ADD_ADDRESS_REQUEST_CODE) {
            if (resultCode == ADD_ADDRESS_RESULT) {
                AddressHandler.requestAddressList();
            }
        } else if (requestCode == MODIFY_ADDRESS_REQUEST_CODE) {
            if (resultCode == MODIFY_ADDRESS_RESULT) {
                AddressHandler.requestAddressList();
            }
        }
    }

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.rv_address)
    RecyclerView addressRv;
    AddressListAdapter adapter;

    @BindView(R.id.btn_new_address)
    Button newAddressBtn;

    @OnClick({R.id.btn_new_address})
    public void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.btn_new_address: {
                startForResult(new AddressEditFragment(), ADD_ADDRESS_REQUEST_CODE);
            }
            break;
        }
    }

    CancelConfirmDialog dialog = null;

    private void initDialog() {
        dialog = new CancelConfirmDialog();
        Bundle bundle = new Bundle();
        bundle.putString("content", _mActivity.getString(R.string.delete_address_tip));
        dialog.setArguments(bundle);
        dialog.setListener(this);
    }

    private void initView() {
        toolbar.setNavigationOnClickListener(v -> pop());
        adapter = new AddressListAdapter(R.layout.item_address_list);
        adapter.setCheckChangeListener((int id, boolean isChecked) -> {
            if (isChecked) {
                AddressHandler.setDefaultAddress(id);
            }
        });
        adapter.setOnItemChildClickListener((BaseQuickAdapter adapter, View view, int position) -> {
            AddressBean addressBean = (AddressBean) adapter.getData().get(position);
            switch (view.getId()) {
                case R.id.tv_edit_address: {
                    AddressEditFragment fragment = new AddressEditFragment();
                    Bundle bundle = new Bundle();
                    bundle.putInt("id", addressBean.getId());
                    fragment.setArguments(bundle);
                    startForResult(fragment, MODIFY_ADDRESS_REQUEST_CODE);
                }
                break;
                case R.id.tv_delete_address: {
                    deleteIndex = position;
                    deleteId = addressBean.getId();
                    if (dialog == null) {
                        initDialog();
                    }
                    dialog.show(getSupportDelegate().getActivity().getSupportFragmentManager(), "");
                }
                break;
                case R.id.tv_address: {
                    if (startType == 1) {
                        AddressBean bean = (AddressBean) adapter.getData().get(position);
                        Bundle bundle = new Bundle();
                        bundle.putParcelable("address_bean", bean);
                        setFragmentResult(RESULT_OK, bundle);
                        pop();
                    }
                }
                break;
            }
        });
        addressRv.setLayoutManager(new LinearLayoutManager(getContext()));
        addressRv.setAdapter(adapter);

        Spannable spannable = new SpannableString(getResources().getString(R.string.new_address));
        spannable.setSpan(new AbsoluteSizeSpan(50), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        newAddressBtn.setText(spannable);

    }

    private int deleteIndex = -1;
    private int deleteId = -1;

    @Override
    public void onConfirm() {
        if (deleteIndex != -1) {
            //调用后台提供的接口，删除后台地址数据
            AddressHandler.deleteAddress(deleteId);
        }
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    @Override
    public void onCancel() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotAddressList(GotAddressList event) {
        adapter.setNewData(event.getAddressList());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeletedAddress(DeletedAddress event) {
        if (event.getResult() == Flag.Result.SUCCEED) {
            adapter.remove(deleteIndex);
            Toast.makeText(getContext(), "删除成功!", Toast.LENGTH_SHORT).show();
        } else if (event.getResult() == Flag.Result.FAILURE) {
            Toast.makeText(getContext(), "删除失败!", Toast.LENGTH_SHORT).show();
        }
        deleteIndex = -1;
        deleteId = -1;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSetDefault(SetDefaultAddressResult event) {
        if (event.getResult() == Flag.Result.SUCCEED) {
            Toast.makeText(getContext(), "设置默认成功!", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getContext(), "设置默认失败!", Toast.LENGTH_SHORT).show();
        }
        AddressHandler.requestAddressList();
    }
}
